package com.he1618.boot3.app;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    public static void main(String[] args) throws InterruptedException {
        // 初始化 CountDownLatch，计数器设置为2
        CountDownLatch latch = new CountDownLatch(2);

        // 启动两个线程
        Thread thread1 = new Thread(new Worker(latch, "Worker 1"));
        Thread thread2 = new Thread(new Worker(latch, "Worker 2"));

        thread1.start();
        thread2.start();

        // 主线程等待两个线程完成
        latch.await();

        System.out.println("All workers have finished their tasks. Main thread continues.");
    }

    static class Worker implements Runnable {
        private final CountDownLatch latch;
        private final String name;

        public Worker(CountDownLatch latch, String name) {
            this.latch = latch;
            this.name = name;
        }

        @Override
        public void run() {
            // 模拟工作任务
            try {
                Thread.sleep(2000);
                System.out.println(name + " has completed its task.");
            } catch (InterruptedException e) {
                e.printStackTrace();
            } finally {
                // 计数器递减
                latch.countDown();
            }
        }
    }
}
